from flask import Blueprint, jsonify, request
from models import Suggestion, Website, Category
from extensions import db
from flask_jwt_extended import jwt_required, get_jwt_identity

api = Blueprint('suggestion_api', __name__)

@api.route('/', methods=['GET'])
@jwt_required()
def get_suggestions():
    page = request.args.get('page', default=1, type=int)
    limit = request.args.get('limit', default=10, type=int)

    query = Suggestion.query.order_by(Suggestion.id)
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    for s in pagination.items:
        temp = s.to_dict()
        print(temp)
    return jsonify({
        "code": 0,
        "msg": "查询成功",
        "page": page,
        "limit": limit,
        "count": pagination.total,
        "data": [s.to_dict() for s in pagination.items]
    })


@api.route('/<int:id>/handle', methods=['POST'])
@jwt_required()
def handle_suggestion(id):
    suggestion = Suggestion.query.get_or_404(id)
    first_cat = Category.query.first()
    if not first_cat:
        return jsonify({'error': '请先添加分类'}), 400
    sug = Website(name=suggestion.website, url=suggestion.website, category_id=first_cat.id)
    sug.is_deleted  = False
    sug.status = 'inactive'
    sug.handled = True
    db.session.add(sug)
    db.session.commit()
    return jsonify({'message': '已处理'})
